package initialize

import (
	"encoding/json"
	"fmt"
	"github.com/nacos-group/nacos-sdk-go/v2/clients"
	"github.com/nacos-group/nacos-sdk-go/v2/common/constant"
	"github.com/nacos-group/nacos-sdk-go/v2/vo"
	"goods_srv/appconfig"
	"goods_srv/types"
	"os"
)

var NacosDate types.Nacos

func InitNacos() {

	os.MkdirAll("./tmp/nacos/log", 0777)
	os.MkdirAll("./tmp/nacos/cache", 0777)

	conf := appconfig.Conf.NacosConfig

	//create clientConfig
	clientConfig := constant.ClientConfig{
		NamespaceId:         conf.NacosName, //we can create multiple clients with different namespaceId to support multiple namespace.When namespace is public, fill in the blank string here.
		TimeoutMs:           5000,
		NotLoadCacheAtStart: true,
		LogDir:              "./tmp/nacos/log",
		CacheDir:            "./tmp/nacos/cache",
		LogLevel:            "debug",
	}

	// At least one ServerConfig
	serverConfigs := []constant.ServerConfig{
		{
			IpAddr:      conf.Host,
			ContextPath: "/nacos",
			Port:        uint64(conf.Port),
			Scheme:      "http",
		},
	}

	// Create config client for dynamic configuration
	configClient, err := clients.CreateConfigClient(map[string]interface{}{
		"serverConfigs": serverConfigs,
		"clientConfig":  clientConfig,
	})
	/*	configClient, err := clients.NewConfigClient(
		vo.NacosClientParam{
			ClientConfig:  &clientConfig,
			ServerConfigs: serverConfigs,
		},
	)*/

	if err != nil {
		panic(err)
		return
	}

	content, err := configClient.GetConfig(vo.ConfigParam{
		DataId: conf.DataId,
		Group:  conf.Group})

	if err != nil {
		fmt.Println("nacos连接失败")
		panic(err)
		return
	}
	fmt.Println("nacos连接成功")

	err = json.Unmarshal([]byte(content), &NacosDate)

	if err != nil {
		panic(err)
		return
	}

	fmt.Println(content)
}
